package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String contextPath = request.getContextPath();
        StringBuffer requestURL = request.getRequestURL();
        String requestURI = request.getRequestURI();
        String referer = request.getHeader("Referer");

        String method = request.getMethod();
        Enumeration<String> parameterNames = request.getParameterNames();
        String queryString = request.getQueryString();
        String parameter = request.getParameter("id");
        //如何解决放行哪些不需要拦截的请求:自定义注解,对不需要进行拦截的请求加上该注解,从而直接放行
        //判断请求的方法是否包含@NoAuthorization注解,包含该注解不需要做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (null != handlerMethod.getMethod().getAnnotation(NoAuthorization.class)) {
                //方法上加了该注解,直接放行
                return true;
            }
        }

        String token = request.getHeader("Authorization");
        User user = userService.queryUserByToken(token);
        if (null == user) {
            response.setStatus(401);//无权限
            return false;
        }

        //将user存储到当前线程中
        UserThreadLocal.set(user);
        return true;
    }
}
